package com.easyfun.healthmagicbox.bluetooth.meng;

import com.easyfun.healthmagicbox.bluetooth.MessageParser;

public class MengMessageParser extends MessageParser<MengMessage>{

	
	@Override
	public MengMessage parse(byte[] buffer1, int len) {
		//copy into inner buffer
		System.arraycopy(buffer1, 0, innerBuffer, innerLen, len);
		innerLen = innerLen + len;
		byte[] oneMsg = getIntegratedMessage();
		if ((oneMsg == null)||(oneMsg.length < 1))
			return null;
		
		MengMessage result = new MengMessage();
		
		result.setRawBytes(oneMsg);
		result.fillin();
		
		
		return result;
	}
	/**
	 * 
	 * @param buffer
	 * @param oneMessage
	 * @return
	 * 
	 * _W:75kg_
	 * _H:123mm;L:75mm;B:80_
	 * _G:4.7_
	 */
	@Override
	protected byte[] getIntegratedMessage( ) {

		
		int begin = -1;
		int end = -1;
		for (int i = 0; i < innerBuffer.length; i++) {
			byte b = innerBuffer[i];
			if (b=='_')
			{
				if (begin == -1)
				{
					begin = i;
				}else 
				{
					if (end == -1)
						end = i + 1;
				}
				if ((begin != -1)&&(end != -1))
				{
					//one whole message.
					break;
				}
			}
		}

		int msgLen = end - begin;	
		if (msgLen < 1)
			return null;
		
		return rearrangeBuffer(begin,end);
	}
}
